//
// Created by v on 19-6-13.
//

#include "OAVImgOptsSimple.h"

#include "utils/cm_logprint.h"

using namespace std;
using namespace cv;

OAVImgOptsSimple::OAVImgOptsSimple(int argc, char **args) : OAVBase(argc, args)
{
}

int OAVImgOptsSimple::do_func(const char *filename)
{
    cminfo("start with filename [%s]\n", filename);
    //    do_bitwise(filename);
    do_estimatePI();
    return 0;
}

int OAVImgOptsSimple::do_bitwise(const char *filename)
{
    cv::Mat grayimg = cv::imread(filename, cv::IMREAD_GRAYSCALE);

    cv::imshow("gray", grayimg);

    cv::Mat mask(grayimg.rows, grayimg.cols, CV_8UC1, cv::Scalar(0, 0, 0));
    cv::circle(mask, cv::Point(grayimg.rows / 4, grayimg.cols / 2), 150, 225,
               -1);

    cv::imshow("mask", mask);

    cv::Mat r;
    cv::bitwise_and(grayimg, mask, r);

    const uchar white = 255;
    for (int i = 0; i < r.rows; i++)
    {
        for (int j = 0; j < r.cols; j++)
        {
            if (!mask.at<uchar>(i, j))
            {
                r.at<uchar>(i, j) = white;
            }
        }
    }
    cv::imshow("Result", r);
    cv::waitKey(0);
    return 0;
}

int OAVImgOptsSimple::do_estimatePI()
{
    const int side    = 100;
    const int npixels = 80000;

    int i, j;
    Mat s1 = Mat::zeros(side, side, CV_8UC1);
    Mat s2 = s1.clone();
    circle(s1, Point(side / 2, side / 2), side / 2, 255, -1);

    imshow("s1", s1);

    for (int k = 0; k < npixels; k++)
    {
        i                  = rand() % side;
        j                  = rand() % side;
        s2.at<uchar>(i, j) = 255;
    }

    Mat r;
    bitwise_and(s1, s2, r);

    imshow("s2", s2);
    imshow("r", r);

    int   Acircle = countNonZero(r);
    int   Asqure  = countNonZero(s2);
    float Pi      = 4 * (float)Acircle / Asqure;

    cminfo("Estimated value of Pi: [%f]\n", Pi);
    waitKey();
    return 0;
}
